<?php

/////////////////////////////////////////////////////////////////
// SpeedPHP����PHP���, Copyright (C) 2008 - 2010 SpeedPHP.com //
/////////////////////////////////////////////////////////////////

/**
 * db_mssql MsSQL��ݿ����֧��
 */
class db_mssql {

    /**
     * ��ݿ����Ӿ��
     */
    public $conn;

    /**
     * ִ�е�SQL����¼
     */
    public $arrSql;

    /**
     * ��SQL����ȡ��¼���������
     * 
     * @param sql  ִ�е�SQL���
     */
    public function getArray($sql) {
//		dump($sql);
        $result = $this->exec($sql);
//                while($row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC))
//{
//	//if($row['id'] == ''){
//	//	echo "û�����";
//	//}else{
// 		echo $row['skey']."-".$row['province']."-".$row['city']."-".$row['areacode']."<br/>";
//	//}
//}
//		dump($result);
        //if( !$result)return FALSE;
//		dump(sqlsrv_num_rows($result));
        if (!sqlsrv_num_rows($result) === false)
            return FALSE;
//		dump(2);
//                $row_count = sqlsrv_num_rows( $stmt );
//                dump($row_count);
        $rows = array();
        while ($rows[] = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {}
        sqlsrv_free_stmt($result);
        array_pop($rows);
        return $rows;
    }
public function getProcess($sql,$ary) {
//        $sql = $this->translimit($sql);	
		$result = sqlsrv_query($this->conn, $sql,$ary);
		

		if ($result) {
//var_dump($result);
		while ($rows[] = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC) ) {}
//var_dump(1);
//var_dump($rows);
//       sqlsrv_free_stmt($result);
//$next_result=sqlsrv_next_result($result);
//if( $next_result )
//{
//     echo "\nReview information for product ID .---\n";
//     while ($rows1[] = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {}
//}
//elseif( is_null($next_result))
//{
//     echo "No more results.\n";
//}
//else
//{
//     echo "Error in moving to next result.\n";
//     die(print_r(sqlsrv_errors(), true));
//}


//var_dump(2);
//var_dump($rows1);
        array_pop($rows);
		$resultdata=$rows;

				return $resultdata;
		} else {
			spError("{$sql}<br />ִ�д���: " . sqlsrv_errors(), true);
		}
    }
    
function arrIconv($arr, $fromCharset, $toCharset){
    if(is_array($arr)){
        $arr1 = array();
//         dump('yes->'.$arr);
        foreach($arr as $key => $value){
            $key = iconv($fromCharset, $toCharset, $key);
            $arr1[$key] = $this->arrIconv($value, $fromCharset, $toCharset);
        }
    }else{
        //if($arr!=''){
//            dump('no->'.$arr);
           $arr1 = iconv($fromCharset, $toCharset, $arr); 
       // }
    }
    return $arr1;
}
    /**
     * ���ص�ǰ�����¼������ID
     */
    public function newinsertid() {
        $result = $this->getArray("select @@IDENTITY as sptmp_newinsert_id");
        return $result[0]['sptmp_newinsert_id'];
    }

    /**
     * ��ʽ����limit��SQL���
     */
    public function setlimit($sql, $limit) {
        if (!eregi(",", $limit))
            $limit = '0,' . $limit;
        $sql .= " LIMIT {$limit}";
        return $this->translimit($sql);
//        return $this->translimit($sql);
    }

    /**
     * ִ��һ��SQL���
     * 
     * @param sql ��Ҫִ�е�SQL���
     */
    public function exec($sql) {
        $sql = $this->translimit($sql);
        //sqlsrv_query($this->conn, 'set names utf-8');
        $this->arrSql[] = $sql;

        if ($result = sqlsrv_query($this->conn, $sql)) {

            return $result;
        } else {
            spError("{$sql}<br />ִ�д���: " . sqlsrv_errors(), true);
        }
    }

    /**
     * ����Ӱ������
     */
    public function affected_rows() {
        return sqlsrv_rows_affected($this->conn);
    }

    /**
     * ��ȡ��ݱ�ṹ
     *
     * @param tbl_name  �����
     */
    public function getTable($tbl_name) {
        $result = $this->getArray("SELECT syscolumns.name FROM syscolumns, systypes WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = object_id('{$tbl_name}')");
        $columns = array();
        foreach ($result as $column)
            $columns[] = array('Field' => $column['name']);
        return $columns;
    }

    /**
     * ���캯��
     *
     * @param dbConfig  ��ݿ�����
     */
    public function __construct($dbConfig) {
        if (!function_exists('sqlsrv_connect'))
            spError('PHP����δ��װMSSQL����⣡');
        //$linkfunction = 'sqlsrv_connect';
        //$this->conn = $linkfunction($dbConfig['host'], $dbConfig['login'], $dbConfig['password']) or spError("��ݿ����Ӵ��� : " . sqlsrv_errors()); 
        $connectionInfo = array("UID" => $dbConfig['login'], "PWD" => $dbConfig['password'], "Database" => $dbConfig['database']);
        $this->conn = sqlsrv_connect($dbConfig['host'], $connectionInfo) or spError("�޷��ҵ���ݿ⣬��ȷ����ݿ������ȷ��");
        //sqlsrv_query($this->conn, 'set names utf-8');
    }

    /**
     * �������ַ���й���
     *
     * @param value  ֵ
     */
    public function __val_escape($value, $quotes = FALSE) {
        if (is_null($value))
            return 'NULL';
        if (is_bool($value))
            return $value ? 1 : 0;
        if (is_int($value))
            return (int) $value;
        if (is_float($value))
            return (float) $value;
        if (@get_magic_quotes_gpc())
            $value = stripslashes($value);
        $value = str_replace("'", "''", $value);
        $value = str_replace("\0", "[NULL]", $value);
        if ($quotes)
            $value = "'{$value}'";
        return $value;
    }

    /**
     * ��������
     */
    public function __destruct() {
//		if( TRUE != $dbConfig['persistent'] )@mssql_close($this->conn);
        if (TRUE != $dbConfig['persistent'])
            sqlsrv_close($this->conn);
    }

    /**
     * ת��MSSQL��LIMIT����ת������
     */
    function translimit($sql) {
        if (preg_match('/ limit /i', $sql)) {
            //ȥ����ո� 
            while (preg_match("/  /", $sql))
                $sql = str_replace("  ", " ", $sql);
            $sql_array = explode(" ", $sql);
            //ȡ�ò�����Ҫ���������� 
            $i = 0;
            while (isset($sql_array[$i]) && $sql_array[$i]) {
                if (strtolower($sql_array[$i]) == "from")
                    $from_id = $i;
                if (strtolower($sql_array[$i]) == "limit")
                    $limit_id = $i;
                if (strtolower($sql_array[$i]) == "order")
                    $order_id = $i;
                $i++;
            }
            $last_id = $i - 1;
            $two_num = explode(",", $sql_array[$limit_id + 1]);
            $totle_num = $two_num[0] + $two_num[1];

            $sql_return = "SELECT ";
            for ($i = 1; $i <= $from_id; $i++) {
                $sql_return .= $sql_array[$i];
                $sql_return .= " ";
            }
            $sql_return .= " ( SELECT TOP {$two_num[1]} ";
            for ($i = 1; $i <= $from_id; $i++) {
                $sql_return .= $sql_array[$i];
                $sql_return .= " ";
            }
            $sql_return .=" ( SELECT TOP {$totle_num} ";
            for ($i = 1; $i < $limit_id; $i++) {
                $sql_return .= $sql_array[$i];
                $sql_return .= " ";
            }
            $sql_return .= " ) AS SPTMP_MSSQL_TOTLERESULT ";
            if (preg_match("/ desc /i", $sql)) {
                for ($i = $from_id + 2; $i < $limit_id; $i++) {
                    if (strtolower($sql_array[$i]) == "desc")
                        continue;
                    $sql_return .= $sql_array[$i];
                    $sql_return .= " ";
                }
            }else {
                for ($i = $from_id + 2; $i < $limit_id; $i++) {
                    $sql_return .= $sql_array[$i];
                    $sql_return .= " ";
                    if ($i == $order_id + 2)
                        $sql_return .= " DESC ";
                }
            }
            $sql_return .= " ) AS SPTMP_MSSQL_ALLRESULT ";
            for ($i = $from_id + 2; $i < $limit_id; $i++) {
                $sql_return .= $sql_array[$i] . " ";
            }
            return iconv('utf-8','gb2312',$sql_return);
        } else {
            return iconv('utf-8','gb2312',$sql);
        }
    }

}
